<template>
  <div class="template-panel">
    <w-form-validate @on-validate="onSave">
      <div class="e-item">
        <span class="title"><em>*</em>模板名称</span>
        <div class="dis-block">
          <w-input :holder="`请填写`" rule="isEmpty" error="请输入模板名称" v-model="params.trans_name"></w-input>
        </div>
      </div>
      <div class="e-item">
        <span class="title"><em>*</em>商品产地</span>
        <div class="dis-block" style="width: auto">
          <w-area-picker v-model="params.areaId"></w-area-picker>
          <!-- <w-select></w-select> -->
        </div>
      </div>
      <div class="e-item" style="margin-bottm: 14px;">
        <span class="title">发货时间</span>
        <div class="dis-block">
          <w-select :options="timesOptions" v-model="params.trans_time"></w-select>
        </div>
        <i>设定宝贝发货时间，不仅可避免发货咨询与纠纷，还能促进成交</i>
      </div>
      <div class="e-item">
        <span class="title"><em>*</em>是否包邮</span>
        <div class="dis-block">
          <span><w-radio name='freight' :label='0' v-model="params.isfree">自定义运费</w-radio></span>
          <w-radio name='freight' :label='1' v-model="params.isfree">卖家承担运费</w-radio>
        </div>
      </div>
      <div class="e-item">
        <span class="title"><em>*</em>计价方式</span>
        <div class="dis-block">
          <span><w-radio name='price' :label='0' v-model="params.trans_type">按件数</w-radio></span>
          <w-radio name='price' :label='1' v-model="params.trans_type">按重量</w-radio>
        </div>
      </div>
      <div class="e-item">
        <span class="title" style="vertical-align: top;">运送方式</span>
        <div class="tmp">
          <span class="transport-box">
            <w-radio name='transport' :label="1" v-model="params.radio">快递</w-radio>
          </span>
          <div class="rule" v-if="params.radio == '1'">
            <carriage-rule v-model="params.transList" :type="params.trans_type"></carriage-rule>
          </div>
          <span class="transport-box">
            <w-radio name='transport' :label="2" v-model="params.radio">EMS</w-radio>
          </span>
          <div class="rule" v-if="params.radio == '2'">
            <carriage-rule v-model="params.transList" :type="params.trans_type"></carriage-rule>
          </div>
          <w-radio name='transport' :label="0" v-model="params.radio">平邮</w-radio>
          <div class="rule" v-if="params.radio == '0'">
            <carriage-rule v-model="params.transList" :type="params.trans_type"></carriage-rule>
          </div>
        </div>
        <!-- <i>除指定地区外，其他地区的运费采用“默认运费”</i> -->
      </div>
      <div style="margin: 70px;">
        <button type="submit" class="btn">确认</button>
        <button type="reset" class="btn colse" @click="onCancel">取消</button>
      </div>
    </w-form-validate>
  </div>
</template>

<script>
import carriageRule from './components/carriageRule'
import { apiDeliveryMange } from 'js/api'
import { session } from 'js/util'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      // 发货时间
      timesOptions: [],
      freightInfo: {},
      params: {
        accessToken: this.$store.getters.token || '',
        threeMenuCode: this.$route.query.three || '',
        id: Number(this.$route.query.freightid) || null,
        areaId: '',
        trans_name: '',
        trans_time: '',
        trans_type: '0',
        radio: null,
        isfree: '0',
        transList: []
      }
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  created() {
    /**
     * 获取发货时间
     */
    this.timesOptions = session.get('devliver-time')
    if (!this.timesOptions || this.timesOptions.length == 0) {
      apiDeliveryMange.apiGetDevTime().then(data => {
        this.timesOptions = data.data || []
        this.timesOptions = this.timesOptions.map(time => {
          return {
            label: time.dataName,
            value: time.dataValue
          }
        })
        session.set('devliver-time', this.timesOptions)
      })
    }
    /**
     * 修改物流时，获取数据
     */
    if (this.$route.query.freightid) {
      apiDeliveryMange.apiDeliveryInfo(this.token, Number(this.$route.query.freightid), this.$route.query.three).then(data => {
        this.params = Object.assign(this.params, data.data || {})
        this.params.areaId = `${this.params.transAreaInfo.firstAreaId},${this.params.transAreaInfo.secondAreaId},${this.params.transAreaInfo.thirdAreaId}`
      })
    }
  },
  methods: {
    /**
     * 校验物流模板填写的数据是否完整
     */
    validateCarriageTmpl(tmpl) {
      // 如果当前模板是空，则此模板是完整的（之前有非空检验）
      if (!tmpl || tmpl.length == 0) {
        return true
      }

      // 设置为完整的标记
      let isComplete = true

      // 遍历模板，如果模板中有为填写的字段
      tmpl.forEach((v) => {
        let reg = /^[0-9]*$/
        // 如果运费件数和运费价格没有填写，则设置标志位是false
        if (!v.trans_add_fee || !v.trans_add_weight || !v.trans_fee || !v.trans_weight || v.city_name == '未添加地区' || !reg.test(v.trans_add_fee) || !reg.test(v.trans_add_weight) || !reg.test(v.trans_fee) || !reg.test(v.trans_weight) || v.trans_add_fee == 0 || v.trans_add_weight == 0 || v.trans_fee == 0 || v.trans_weight == 0) {
          isComplete = false
        }
      })
      return isComplete
    },
    /**
     * 当前值是否被选中
     *
     * @params { Number }  value  需要判断的值
     * @return { Boolean } value  是否被选中
     */
    isSelected(value) {
      return value == '0' || value == '1' || value == '2'
    },
    /**
     * 新增，修改
     */
    onSave() {
      const tip = this.$route.query.freightid ? '修改成功' : '新增成功'
      // 如果地区没有选择，则弹框提示
      if (!this.params.trans_name) {
        this.$toast('请输入模板名称')
        return
      }

      // 如果地区没有选择，则弹框提示
      if (!this.params.areaId) {
        this.$toast('请选择地区')
        return
      }

      // 如果地区没有选择，则弹框提示
      if (!this.isSelected(this.params.isfree)) {
        this.$toast('请选择是否包邮')
        return
      }

      // 如果计价方式没有选择，则弹框提示
      if (!this.isSelected(this.params.trans_type)) {
        this.$toast('请选择计价方式')
        return
      }
      
      // 若运费方式为空，则提示
      if (!this.isSelected(this.params.radio)) {
        this.$toast('请选择运费方式')
        return
      }

      // 如果当前用户选择了自定义运费
      if (this.params.isfree == '0') {
        // 如果没有输入模板，则弹框提示
        if (!this.params.transList || this.params.transList.length == 0) {
          this.$toast('请配置运费模板')
          return
        }

        // 检验快递模板是否填写完整
        if (!this.validateCarriageTmpl(this.params.transList)) {
          this.$toast('运费模板未填写完整或信息错误')
          return
        }
      }

      // 将原本的值拷贝一份
      let params = Object.assign({}, this.params)
      // 分割地区id
      let areaIdList = params.areaId.split(',')
      // 将最后一个地区id赋值给id
      params.areaId = areaIdList[areaIdList.length - 1]
      // 请求接口
      apiDeliveryMange.apiDeliverySave(params).then(data => {
        this.$toast(tip, () => {
          this.$router.push(`./list?three=${this.$route.query.three}`)
        })
      })
    },
    /**
     * 取消
     */
    onCancel() {
      this.$router.go(-1)
    }
  },
  components: {
    'carriage-rule': carriageRule
  }
}
</script>

<style lang="scss" scoped>
@import '../../scss/_var.scss';
.template-panel {
  padding: 20px 10px;
  .e-item {
    display: block;
    margin-bottom: 20px;
    margin-left: 0;
    em,i {
      color: $color-main;
    }
    i {
      font-size: 10px;
      display: block;
      margin-top: 7px;
      margin-left: 80px;
    }
    .title {
      width: 66px;
      font-size: 14px;
      display: inline-block;
      text-align: right;
    }
    .dis-block {
      display: inline-block;
      width: 284px;
      margin-left: 10px;
      span {
        display: inline-block;
        width: 135px;
      }
      .transport-box {
        display: inline-block;
        width: 70px;
        margin-right: 35px;
      }
    }
    .tmp {
      display: inline-block;
      margin-left: 10px;
      width: 92%;
    }
  }
  .rule {
    margin: 10px 0
  }
}
</style>
